package com.winchain.chainbill.bill.biz.transfer.service.impl;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.bill.base.po.CbXfe;
import com.winchain.chainbill.bill.base.service.CbXfeService;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillTranEvent;
import com.winchain.chainbill.bill.biz.transfer.service.BillXfeEventService;
import com.winchain.chainbill.bill.biz.transfer.vo.BillTransfer;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("billXfeEventService")
public class BillXfeEventServiceImpl
  implements BillXfeEventService
{
  @Autowired
  private CbXfeService cbXfeService;
  
  public BillTranEvent<CbXfe> getBillTranEvent(String billId, boolean callback)
  {
    List<BillTransfer> bills = this.cbXfeService.selectBillXfesByBillIdAndState(billId, "1");
    if ((bills == null) || (bills.size() == 0)) {
      throw new UnCheckMsgException("����������������������");
    }
    Bill<CbXfe> prntBill = new Bill();
    
    List<Bill<CbXfe>> children = new ArrayList();
    for (BillTransfer billXfe : bills) {
      if (billId.equals(billXfe.getPrntId()))
      {
        Bill<CbXfe> childBill = new Bill();
        if (billXfe.getXfeId() == null) {
          billXfe.setOptSeq(billXfe.getCbOptSeq());
        }
        childBill.setRec(billXfe.getRec());
        childBill.setSource(billXfe.getTransfer());
        
        children.add(childBill);
      }
      else
      {
        if (billXfe.getXfeId() == null)
        {
          billXfe.setOptSeq(billXfe.getCbOptSeq());
          if (!callback)
          {
            billXfe.setBuyerId(CommonDataUtil.getCurEntId());
            billXfe.setBuyerNm(CommonDataUtil.getCurEntName());
          }
        }
        prntBill.setRec(billXfe.getRec());
        prntBill.setSource(billXfe.getTransfer());
      }
    }
    Object event = new BillTranEvent(prntBill);
    ((BillTranEvent)event).setChildren(children);
    
    return (BillTranEvent<CbXfe>)event;
  }
}
